package com.util;

import java.util.Calendar;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentSkipListSet;

import org.apache.log4j.Logger;


public class CalcIndex extends TimerTask
{
	Logger log = null;
	private static Timer timer=new Timer();
	private static long period=2160*1000;//36分钟
	private static int day=9;//每月定点哪天计算
	private static int startHour=-1;//每天定点哪个小时计算 -1表示不定时
	private static int startLast=-1;//每天定点哪个小时计算 -1表示不定时
	private static int delay=2*60;//延迟多少秒后执行;
	static {		
		String p = "";
		if (!(p == null || p.equals(""))) {
			try {
				String prop[]=p.split(",");
				period = Math.round(3600*1000*(Float.parseFloat(prop[0])));
				day=Math.round(prop.length>=2?Integer.parseInt(prop[1]):9);
				startHour=(prop.length>=3)?Math.round(Integer.parseInt(prop[2])):-1;
				startLast=prop.length>=4?Integer.parseInt(prop[3]):-1;
			} catch (Exception e) {
				period = 2160*1000;
				day=9;
				startHour=-1;
				startLast=-1;
			}
		}		
	}
	public long getPeriod() {
		return period;
	}
	public int getDay() {
		return day;
	}
	public int getStartHour() {
		return startHour;
	}
	public int getStartLast() {
		return startLast;
	}
	public int getDelay() {
		return delay;
	}

	private static CalcIndex inst=new CalcIndex();
	private CalcIndex(){	
		//延迟delay秒后以固定周期period启动线程计算一次
		timer.schedule(this, delay*1000, period);		
	}
	public static CalcIndex inst(){
		return inst;
	}
	
	@Override
	public boolean cancel() {
		return super.cancel();
	}

	@Override
	public void run() {
		try {
			Calendar calendar = Calendar.getInstance();
			// 每个月9号定时计算指标
			if (calendar.get(Calendar.DAY_OF_MONTH) == day && (startHour==-1 || calendar.get(Calendar.HOUR_OF_DAY)==startHour-1 || calendar.get(Calendar.HOUR_OF_DAY)==startHour) ) {
				synchronized (this) {			
					log.info(delay + "秒后启动指标计算……");
					// 定时器跑到8（9-1）点钟的时候，延迟至9点开始计算
					if (calendar.get(Calendar.HOUR_OF_DAY) == startHour - 1) {
						Thread.sleep(delay * 1000 + (60 - calendar.get(Calendar.MINUTE))*60*1000);
					} else if (calendar.get(Calendar.HOUR_OF_DAY) == startHour) {
						// 如果此时是startHour（9点）,说明是8点前的某些时候有部署动作，且部署成功后时间到了9点，
						// 则立即启动计算线程
					} else
						Thread.sleep(delay * 1000);// 其它情况，如不限时计算，则线程先准备一下之后再计算
					long startTime = System.currentTimeMillis();
					int year = calendar.get(Calendar.YEAR);
					int month = calendar.get(Calendar.MONTH);
					if (month == 0) {
						year = year - 1;
						month = 12;
					}
					String cycle=""+year+(month>9?month:"0"+month);
					Set<String> cycleSet=new ConcurrentSkipListSet<String>();
					cycleSet.add(cycle);
					List<Integer> list = DBUtil.queryForList("select distinct(orgid) from globalindex where cycle="+cycle, Integer.class);
					
					for (int organid : list) {
						long time1=System.currentTimeMillis();
						
						long time2=System.currentTimeMillis();
						String organIdMsg = year + "-" + month + " 的指标处理完成！处理的中心为：" + organid + " 耗时 " + (time2-time1) + " 毫秒";						
						log.info(organIdMsg);
					}
					long endTime = System.currentTimeMillis();
					String msg = year + "-" + month + " 的所有中心的指标处理完成！处理的中心为[" + (list.size() == 0 ? "" : StringUtils.joinBySplit(list)) + "] 耗时：" + (endTime - startTime)
							+ " 毫秒";
					log.info(msg);					
					Calendar calendarEnd = Calendar.getInstance();
					// 如果指标处理完成之后，时间还在计算时间起点（9点），那么让这个线程先睡个觉,这样就不会执行前面if里面（
					// calendar.get(Calendar.HOUR_OF_DAY)==startHour）这个条件了
					if (calendarEnd.get(Calendar.HOUR_OF_DAY) == startHour) {
						Thread.sleep((startLast) * 3600 * 1000);
					}
				}	
			}
		} catch (InterruptedException e) {			
			log.error(e);
		}catch (Exception e) {		
			log.error(e);
		}

	}
	
	public static void main(String[] args) {
		CalcIndex.inst().run();
		try {
			Thread.sleep(60*1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(CalcIndex.inst().cancel());
	}

}
